<?php

if ( !defined( 'CMS_ROOT' ) )
	die;

/**
 * Flexo CMS - Content Management System. <http://flexo.up.dn.ua>
 * Copyright (C) 2008 Maslakov Alexander <jmas.ukraine@gmail.com>
 * Copyright (C) 2008 Philippe Archambault <philippe.archambault@gmail.com>
 * Copyright (C) 2008 Martijn van der Kleijn <martijn.niji@gmail.com>
 *
 * This file is part of Flexo CMS.
 *
 * Flexo CMS is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Flexo CMS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Flexo CMS.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Flexo CMS has made an exception to the GNU General Public License for plugins.
 * See exception.txt for details and the full text.
 */

/**
 * @package Flexo
 * @subpackage plugins.tinymce
 *
 * @author Maslakov Alexandr <jmas.ukraine@gmail.com>
 * @version 0.1
 * @license http://www.gnu.org/licenses/gpl.html GPL License
 * @copyright Maslakov Alexander, 2011
 */
class ImperaviController extends PluginController {

	public function index()
	{
//		$this->setLayout( 'backend' );
	}

	public function images_json( $page_id )
	{
		$images = PIImage::find( array('where' => 'page_id=' . (int) $page_id) );

		$data = array();


		foreach ( $images as $image )
		{
			$data[] = array(
				'thumb' => $image->url( 80, 80 ),
				'image' => $image->url( 800, 600 )
			);
		}
		echo json_encode( $data );
	}

	public function upload()
	{
		require(PLUGINS_ROOT . DIRECTORY_SEPARATOR . 'file_manager/fileuploader/qqUploader.php');

		if ( empty( $_GET['folder'] ) )
		{
			echo json_encode( array('error' => 'Params folder required!') );
		}
		else
		{
			$folder_name = urldecode( str_replace( '..', '', $_GET['folder'] ) );

			// Change charset for russian names (only when os windows)
			if ( PHP_OS == 'WIN' || PHP_OS == 'WINNT' )
				$folder_name = iconv( 'UTF-8', 'CP1251', $folder_name );

			$folder_path = PUBLIC_ROOT . DIRECTORY_SEPARATOR . $folder_name . DIRECTORY_SEPARATOR;

			if ( is_dir( $folder_path ) && !empty( $folder_name ) )
			{
				// list of valid extensions, ex. array("jpeg", "xml", "bmp")
				$allowedExtensions = array('png', 'jpg', 'jpeg', 'gif');
				// max file size in bytes
				//$sizeLimit = 10 * 1024 * 1024;

				$uploader = new qqFileUploader( $allowedExtensions );

				$page_id = empty( $_GET['page_id'] ) ? 0 : $_GET['page_id'];
				$folder_path = $folder_path . $page_id . DIRECTORY_SEPARATOR;
				if ( !is_dir( $folder_path ) )
					mkdir( $folder_path );

				$result = $uploader->handleUpload( $folder_path );


				if ( !empty( $result['filename'] ) )
				{
					$image = new PIImage();
					$image->page_id = $page_id;
					$image->file_name = $result['filename'];

					if ( $image->save() )
					{
						$result['image_id'] = $image->id;
						$result['page_id'] = $page_id;

						echo '<img src="' . $image->url( 800, 600 ) . '" />';
					}
					else
					{
						echo 'Image not saved!';
					}
				}
				else
				{
					echo 'Image not uploaded!';
				}
			}
			else
			{
				echo 'Folder \'' . $folder_name . '\' not valid!';
			}
		}
	}

	public function file_delete( $page_id, $file_name )
	{
		if ( !empty( $file_name ) )
		{
			$file = PUBLIC_ROOT . '/page_images/' . $page_id . '/' . $file_name;

			unlink( $file );
			exit;
		}
	}

	public function file_upload( $page_id )
	{
		if ( !empty( $_FILES['file']['name'] ) )
		{
			$path = PUBLIC_ROOT . '/page_images/' . $page_id . '/';
			$file_size = $_FILES['file']['size'];
			$file_type = $this->info( $_FILES['file']['name'], 'type' );
			$file_name = str_replace( '.' . $file_type, '', $_FILES['file']['name'] );

			// $file_id = md5(date('YmdHis').$file_name);

			$file_name = $this->get_filename( $path, $_FILES['file']['name'], $file_type );


			$file_ico = $this->get_ico( $file_type );

			$file = $path . $file_name;
			copy( $_FILES['file']['tmp_name'], $file );


			echo '<a href="javascript:void(null);" rel="' . $file_name . '" class="redactor_file_link redactor_file_ico_' . $file_ico . '">' . $file_name . '</a>';
		}
	}

	private function get_ico( $type )
	{
		$fileicons = array('other' => 0, 'avi' => 'avi', 'doc' => 'doc', 'docx' => 'doc', 'gif' => 'gif', 'jpg' => 'jpg', 'jpeg' => 'jpg', 'mov' => 'mov', 'csv' => 'csv', 'html' => 'html', 'pdf' => 'pdf', 'png' => 'png', 'ppt' => 'ppt', 'rar' => 'rar', 'rtf' => 'rtf', 'txt' => 'txt', 'xls' => 'xls', 'xlsx' => 'xls', 'zip' => 'zip');

		if ( isset( $fileicons[$type] ) )
			return $fileicons[$type];
		else
			return 'other';
	}

	private function get_filename( $path, $filename, $file_type )
	{
		if ( !file_exists( $path . $filename ) )
			return $filename;

		$filename = str_replace( '.' . $file_type, '', $filename );

		$new_filename = '';
		for ( $i = 1; $i < 100; $i++ )
		{
			if ( !file_exists( $path . $filename . $i . '.' . $file_type ) )
			{
				$new_filename = $filename . $i . '.' . $file_type;
				break;
			}
		}

		if ( $new_filename == '' )
			return false;
		else
			return $new_filename;
	}

	private function info( $file, $key = false )
	{
		$info = array();
		$array = explode( ".", $file );

		//$info['size'] = @filesize( $file );
		//$info['time'] = filectime($file);
		$info['type'] = end( $array );
		$info['name'] = str_replace( '.' . $info['type'], '', $file );
		$info['image'] = false;

		if ( $info['type'] == 'JPG' ||
				$info['type'] == 'jpg' ||
				$info['type'] == 'gif' ||
				$info['type'] == 'png' )
		{
			$info['image'] = true;
		}

		if ( !$key )
			return $info;
		else
			return $info[$key];
	}

}

// end class TinymceController
